package com.mj.base;

import java.util.Map;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.AQUtility;
import com.mj.MJApplaction;
import com.mj.activity.MainActivity;
import com.mj.activity.user.Activity_Login;
import com.mj.bean.ErrorInfo;
import com.mj.http.Json;
import com.mj.http.NetCallback;
import com.mj.http.Url;
import com.mj.util.Constant;
import com.mj.util.DebugLog;
import com.mj.util.Info;
import com.mj.util.NetTools;

public class BaseActivity extends FragmentActivity {
	public AQuery aq;
	public ProgressDialog pd;
	private String TAG;
	protected final int FINISH = 555;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		aq = new AQuery(this);
		// 硬件加速开启
		aq.hardwareAccelerated11();
		TAG = this.getClass().getName();
		DebugLog.i(TAG, "onCreate");
	}

	/***
	 * 当用户登录成功之后的操作
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Constant.LOGIN) {
			switch (requestCode) {
			case Constant.GET: {
				String userkey = "userkey=" + MJApplaction.userInfo.getUserkey();
				String token = "token=" + MJApplaction.userInfo.getToken();
				MJApplaction.url = MJApplaction.url.replace("userkey=", userkey);
				MJApplaction.url = MJApplaction.url.replace("token=", token);
				getJson(MJApplaction.url, MJApplaction.callback, true);
			}
				break;
			case Constant.POST: {
				String userkey = MJApplaction.userInfo.getUserkey();
				String token = MJApplaction.userInfo.getToken();
				MJApplaction.params.put("userkey", userkey);
				MJApplaction.params.put("token", token);
				postJson(MJApplaction.url, MJApplaction.params, MJApplaction.callback, true);
			}
				break;
			default:
				goMain();
				break;
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (isTaskRoot()) {
			long triggerSize = 3000000;
			long targetSize = 2000000;
			AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
		}
	}

	/***
	 * get请求 不需要处理返回数据
	 */
	public void getJson(String url) {
		if (!NetTools.isNetworkConnected(this)) {
			return;
		}
		url = Url.getParams(url, BaseActivity.this);
		aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>());
	}

	/***
	 * post请求 不需要处理返回数据
	 */
	public void postJson(String url, Map<String, Object> params) {
		if (!NetTools.isNetworkConnected(this)) {
			return;
		}
		params = Url.postParams(url, params, BaseActivity.this);
		aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>());
	}

	/***
	 * get请求 返回json数据
	 * 
	 * @param url
	 * @param callback
	 */
	public void getJson(String url, final NetCallback callBack, boolean needLogin) {
		if (needLogin && !Info.isLogin()) {
			goLogin(Constant.GET, callBack, url, null);
			return;
		}
		callBack.onStart();
		if (!NetTools.isNetworkConnected(this)) {
			callBack.onFailure("请确认网络连接是否正常");
			return;
		}
		url = Url.getParams(url, BaseActivity.this);
		aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
			@Override
			public void callback(String url, JSONObject object, AjaxStatus status) {
				if (object != null) {
					if (!hasError(object, callBack)) {
						callBack.onSuccess(object);
					}
				} else {
					callBack.onFailure(status.getMessage());
				}
			}

			@Override
			public void failure(int code, String message) {
				callBack.onFailure(message);
			}
		});
	}

	/***
	 * post请求 返回json数据
	 * 
	 * @param url
	 * @param callback
	 */
	public void postJson(String url, Map<String, Object> params, final NetCallback callBack, boolean needLogin) {
		if (needLogin && !Info.isLogin()) {
			goLogin(Constant.POST, callBack, url, params);
			return;
		}
		callBack.onStart();
		if (!NetTools.isNetworkConnected(this)) {
			callBack.onFailure("请确认网络连接是否正常");
			return;
		}
		params = Url.postParams(url, params, BaseActivity.this);
		aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {
			@Override
			public void callback(String url, JSONObject object, AjaxStatus status) {
				if (object != null) {
					if (!hasError(object, callBack)) {
						callBack.onSuccess(object);
					}
				} else {
					callBack.onFailure("返回数据为空");
				}
			}

			@Override
			public void failure(int code, String message) {
				callBack.onFailure(message);
			}
		});
	}

	/***
	 * 检查返回的Error信息,如存在错误信息,将错误信息作为netcallback的失败方法的参数并调用该方法
	 */
	public boolean hasError(JSONObject object, NetCallback callBack) {
		ErrorInfo errorInfo = Json.getErrorInfo(object);
		switch (errorInfo.getCode()) {
		case 200:
			return false;
		case 501:
			// Intent intent = new Intent(this, Activity_Login.class);
			// startActivity(intent);
		default:
			callBack.onFailure(errorInfo.getErrormessage());
			return true;
		}
	}

	/***
	 * 回调基类
	 * 
	 * @author duanyimin
	 * 
	 */
	public class baseCallBack implements NetCallback {
		public baseCallBack() {
		}

		@Override
		public void onStart() {
			if (pd == null || !pd.isShowing()) {
				pd = new ProgressDialog(BaseActivity.this);
				pd.setMessage("加载中,请稍候");
				pd.setTitle("提示");
				pd.show();
			}
		}

		@Override
		public void onSuccess(JSONObject object) {
			if (pd != null) {
				pd.dismiss();
			}
		}

		@Override
		public void onFailure(String message) {
			if (pd != null) {
				pd.dismiss();
			}
			Toast.makeText(BaseActivity.this, message, Toast.LENGTH_LONG).show();
		}
	}

	/***
	 * 去登录页面之前的设置
	 * 
	 * @param type
	 * @param callBack
	 * @param url
	 * @param params
	 */
	public void goLogin(int type, final NetCallback callBack, String url, Map<String, Object> params) {
		Intent intent = new Intent(this, Activity_Login.class);
		startActivityForResult(intent, type);
		MJApplaction.callback = new NetCallback() {
			@Override
			public void onSuccess(JSONObject object) {
				callBack.onSuccess(object);
				MJApplaction.cleanLoginInfo();
			}

			@Override
			public void onStart() {
			}

			@Override
			public void onFailure(String message) {
				callBack.onFailure(message);
				MJApplaction.cleanLoginInfo();
			}
		};
		MJApplaction.url = url;
		MJApplaction.params = params;
	}

	/***
	 * 返回
	 */

	public void back() {
		finish();
	}

	/***
	 * 返回首页
	 */
	public void goMain() {
		Intent intent = new Intent(this, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	}
}
